package com.itgacl.fastdfs;

import com.itgacl.fastdfs.bean.FastDFSUploadResult;
import com.itgacl.fastdfs.exception.FastDFSException;
import com.itgacl.fastdfs.util.FileUtil;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;

/**
 * 基于Fastdfs上传实现
 * Created by gacl on 2017/10/16.
 */
public class FastdfsFileService{

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(FastdfsFileService.class);

    /**
     * 文件上传后的存储方式
     */
    private static final String STORAG_TYPE = "FastDFS";

    /**
     * 获取FastDFSClient实例
     */
    private FastDFSClient fastDFSClient;

    /**
     * @param fastdfsClientConfigFilePath
     *          fastdfs连接客户端初始化用到的properties配置文件
     */
    public FastdfsFileService(String fastdfsClientConfigFilePath){
        //获取FastDFSClient实例
        fastDFSClient = FastDFSClient.getInstance(fastdfsClientConfigFilePath);
    }

    public FastDFSUploadResult uploadFile(String filePath) {
        File file = new File(filePath);
        return uploadFile(file);
    }

    public FastDFSUploadResult uploadFile(InputStream inputStream, String fileName) {
        Long startTime = System.currentTimeMillis();
        FastDFSUploadResult uploadFile = new FastDFSUploadResult();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        uploadFile.setOriginalFileName(fileName);
        uploadFile.setFileSuffix(ext);
        try {
            byte[] content = new byte[0];
            try {
                content = FileUtil.input2ByteArray(inputStream);
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
            FastDFSFile fastDFSFile = new FastDFSFile(fileName, content, ext);
            //上传文件到fastDFS服务器
            fastDFSClient.uploadFile(fastDFSFile);
            uploadFile.setFileUrl(fastDFSFile.getRemotePath());
            String fileId = fastDFSFile.getGroup() + "/" + fastDFSFile.getStoragePath();
            uploadFile.setFileId(fileId);
            String newFileName = fileId.substring(fileId.lastIndexOf("/")+1);
            uploadFile.setNewFileName(newFileName);
            uploadFile.getExtFieldMap().put("group",fastDFSFile.getGroup());
            uploadFile.getExtFieldMap().put("storagePath",fastDFSFile.getStoragePath());
            uploadFile.setIsUploadSuccess(true);
        } catch (Exception ex) {
            logger.error("将文件上传到FastDFS失败！", ex);
            uploadFile.setIsUploadSuccess(false);
        }
        Long endTime = System.currentTimeMillis();
        uploadFile.setUseTime(endTime-startTime);
        uploadFile.setStorageType(STORAG_TYPE);
        return uploadFile;
    }

    public FastDFSUploadResult uploadFile(File file) {
        String fileName = file.getName();
        Long startTime = System.currentTimeMillis();
        FastDFSUploadResult uploadFile = new FastDFSUploadResult();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        uploadFile.setOriginalFileName(fileName);
        uploadFile.setFileSuffix(ext);
        try {
            byte[] content = new byte[0];
            try {
                content = FileUtil.file2ByteArray(file);
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
            FastDFSFile fastDFSFile = new FastDFSFile(fileName, content, ext);
            //上传文件到fastDFS服务器
            fastDFSClient.uploadFile(fastDFSFile);
            uploadFile.setFileUrl(fastDFSFile.getRemotePath());
            String fileId = fastDFSFile.getGroup() + "/" + fastDFSFile.getStoragePath();
            uploadFile.setFileId(fileId);
            String newFileName = fileId.substring(fileId.lastIndexOf("/")+1);
            uploadFile.setNewFileName(newFileName);
            uploadFile.getExtFieldMap().put("group",fastDFSFile.getGroup());
            uploadFile.getExtFieldMap().put("storagePath",fastDFSFile.getStoragePath());
            uploadFile.setIsUploadSuccess(true);
        } catch (Exception ex) {
            logger.error("将文件上传到FastDFS失败！", ex);
            uploadFile.setIsUploadSuccess(false);
        }
        Long endTime = System.currentTimeMillis();
        uploadFile.setUseTime(endTime-startTime);
        uploadFile.setStorageType(STORAG_TYPE);
        return uploadFile;
    }

    public FastDFSUploadResult uploadFile(byte[] fileByte, String fileName) {
        Long startTime = System.currentTimeMillis();
        FastDFSUploadResult uploadFile = new FastDFSUploadResult();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        uploadFile.setOriginalFileName(fileName);
        uploadFile.setFileSuffix(ext);
        try {
            FastDFSFile fastDFSFile = new FastDFSFile(fileName, fileByte, ext);
            //上传文件到fastDFS服务器
            fastDFSClient.uploadFile(fastDFSFile);
            uploadFile.setFileUrl(fastDFSFile.getRemotePath());
            String fileId = fastDFSFile.getGroup() + "/" + fastDFSFile.getStoragePath();
            uploadFile.setFileId(fileId);
            String newFileName = fileId.substring(fileId.lastIndexOf("/")+1);
            uploadFile.setNewFileName(newFileName);
            uploadFile.getExtFieldMap().put("group",fastDFSFile.getGroup());
            uploadFile.getExtFieldMap().put("storagePath",fastDFSFile.getStoragePath());
            uploadFile.setIsUploadSuccess(true);
        }catch (Exception e){
            logger.error("将文件上传到FastDFS失败！", e);
            uploadFile.setIsUploadSuccess(false);
        }
        Long endTime = System.currentTimeMillis();
        uploadFile.setUseTime(endTime-startTime);
        uploadFile.setStorageType(STORAG_TYPE);
        return uploadFile;
    }

    public List<FastDFSUploadResult> uploadFile(Map<String, InputStream> inputStreamMap){
        try {
            return fastDFSClient.uploadFile(inputStreamMap);
        } catch (FastDFSException e) {
            return null;
        }
    }

    public FastDFSUploadResult uploadNetworkFile(String fileUrl) throws MalformedURLException {
        return uploadNetworkFile(fileUrl,"");
    }

    public FastDFSUploadResult uploadNetworkFile(String fileUrl, String fileExt) throws MalformedURLException {
        //下载网络文件
        byte[] content = FileUtil.downloadNetworkFile(fileUrl);
        String ext;
        if(!isEmpty(fileExt)){
            ext = fileExt;
        }else{
            ext = fileUrl.substring(fileUrl.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        }
        logger.info("ext："+ext);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1).toLowerCase()+"."+ext;
        return uploadFile(content,fileName);
    }

    public int deleteFile(String directory, String fileName) {
        int result = 0;
        try {
            fastDFSClient.deleteFile(directory, fileName);
        } catch (FastDFSException e) {
            result = -1;
        }
        logger.info("deleteFileResult："+result);
        return result;
    }

    public Map<String,Integer> batchDeleteFile(String directory, List<String> lstFileName) {
        Map<String,Integer> resultMap = fastDFSClient.batchDeleteFile(directory, lstFileName);
        logger.info("batchDeleteFileResult："+resultMap);
        return resultMap;
    }

    public byte[] downloadFile(String fileUrl) {
        try {
            //下载网络文件
            return  FileUtil.downloadNetworkFile(fileUrl);
        }catch (Exception e){
            return null;
        }
    }

    public byte[] downloadFile(String directory, String fileName) {
        try {
            return fastDFSClient.downloadFile(directory, fileName);
        } catch (FastDFSException e) {
            return null;
        }
    }

    public void downloadFile(String directory, String fileName, String savePath) {
        byte[] fileByte = downloadFile(directory, fileName);
        if(fileByte != null){
            try {
                FileUtil.saveFile(savePath,fileByte);
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
    }

    private boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}
